Fetch API and it's Method in JS
Fetch API is a modern JavaScript API that allows you to make HTTP requests in a more efficient and powerful way than the traditional XMLHttpRequest object. It provides a simple and intuitive way to fetch data from a server , making it easier to build web applications that rely on data from APIs.
Fetch returns a Promise, which makes it great for working with asynchronous code using .then() or async/await.
Use case: Sending form data, login credentials, etc.
HTTP Methods in Fetch API
Example Usage in Fetch API
Here's how you'd use some of these methods with fetch():
GET Example
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => console.log(data));
POST Example
fetch('https://api.example.com/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John', age: 30 })
});
PUT Example
fetch('https://api.example.com/user/123', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Updated Name', age: 32 })
});
DELETE Example
fetch('https://api.example.com/user/123', {
method: 'DELETE'
});
Why we're using two .then() in Fetch API
.then() # |
What It Does |
1st .then(response => response.json()) |
Handles the raw response object from the server and parses it into JSON. |
2nd .then(data => {...}) |
Uses the parsed data (actual useful content) from the previous step. |